<template>
  <div class="draw-map-tool" v-if="visible">
    <!-- <div class="draw-map-tool-header">
      <h3>绘制地图</h3>
    </div> -->
  </div>
</template>

<script>
import emitter from '@u/event-bus'
import sharedDrawingManager from '@/utils/map/shared-drawing-manager.js'
import mapboxgl, { LngLat } from 'mapbox-gl'
import * as coordtransform from 'coordtransform'
import { nanoid } from 'nanoid'
import { jsonp } from '@/utils/jsonp'
import LocationInfoPopup from '@/components/draw-map/location-info-popup.vue'
import { remove } from 'lodash'

let _map

// 地图API密钥
const MAP_KEY = 'FQWBZ-PJXEU-LRZV2-BUBN5-AFKGO-R6BKQ'

// 标记点数据结构
let markers = []

// 存储已显示的绘制数据
let displayedFeatures = []

export default {
  name: 'DrawMapTool',
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    data: {
      type: Object,
      default: () => ({}),
    },
    templateId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      currentDrawType: null,
      mapReady: false,
      handlingCreate: false,
      isEditMode: false, // 控制是否可编辑
      existingDataShown: false, // 标记是否已显示过现有数据
    }
  },
  watch: {
    data: {
      handler(newData) {
        if (newData && this.mapReady && !this.existingDataShown) {
          this.showExistingData()
          this.existingDataShown = true
        }
      },
      deep: true,
      immediate: true,
    },
    mapReady: {
      handler(isReady) {
        if (isReady && this.data && !this.existingDataShown) {
          // this.showExistingData()
          this.existingDataShown = true
        }
      },
      immediate: true,
    },
  },
  mounted() {
    this.getMapInstance()
  },
  beforeDestroy() {
    emitter.off('map-ready', this.onMapReady)
    this.stopDrawing()
  },
  methods: {
    getMapInstance() {
      const map = emitter.getMap && emitter.getMap()
      if (map) {
        this.onMapReady(map)
      } else {
        emitter.on('map-ready', this.onMapReady)
      }
    },

    onMapReady(map) {
      _map = map
      this.mapReady = true
    },

    // 删除标记点
    deleteMarker(id) {
      const item = markers.find((m) => m.id === id)
      if (item) {
        item.marker.remove()
        item.popup.remove()
        remove(markers, item)
      }
    },

    // 添加标记点（参考draw-map的实现）
    async addMarker(lngLat, addressStr = '') {
      if (!_map) return
      const lng = Number(lngLat.lng.toFixed(6))
      const lat = Number(lngLat.lat.toFixed(6))
      const [l1, l2] = coordtransform.wgs84togcj02(lng, lat)
      const url = `https://apis.map.qq.com/ws/geocoder/v1/?location=${l2},${l1}&key=${MAP_KEY}&get_poi=0`
      let address = addressStr
      const id = nanoid()
      if (!addressStr) {
        try {
          // 添加延迟避免并发请求冲突
          await new Promise(resolve => setTimeout(resolve, Math.random() * 100))
          const res = await jsonp(url, { output: 'jsonp' })
          if (res.status === 0) {
            address = res.result?.formatted_addresses?.recommend || `位置 ${lng.toFixed(4)},${lat.toFixed(4)}`
          } else {
            address = `位置 ${lng.toFixed(4)},${lat.toFixed(4)}`
          }
        } catch (e) {
          address = `位置 ${lng.toFixed(4)},${lat.toFixed(4)}`
        }
      }

      const Constructor = (await import('vue')).default.extend(LocationInfoPopup)
      const popupInstance = new Constructor({
        propsData: {
          pointInfo: [lng, lat],
          address,
          id,
          deleteMarker: this.deleteMarker,
          // disabled: !this.isEditMode, // 根据编辑模式控制是否可删除
        },
      }).$mount()

      const popup = new mapboxgl.Popup({
        anchor: 'bottom',
        closeOnClick: false,
        closeButton: false,
        offset: [0, -10],
        className: 'marker',
        maxWidth: '80px',
      }).setDOMContent(popupInstance.$el)

      popup.setLngLat(lngLat).addTo(_map)

      // const el = document.createElement('div')
      const center = document.createElement('div')
      center.style.width = '16px'
      center.style.height = '16px'
      center.style.backgroundColor = '#00BAFF'
      center.style.borderRadius = '50%'
      center.style.border = '2px solid white'
      // el.style.width = '84px'
      // el.style.height = '84px'
      // el.style.background = 'rgba(0,186,255,.2)'
      // el.style.borderRadius = '50%'
      // el.style.display = 'flex'
      // el.style.justifyContent = 'center'
      // el.style.alignItems = 'center'
      // el.appendChild(center)

      const marker = new mapboxgl.Marker(center).setLngLat(lngLat).addTo(_map)

      markers.push({
        id,
        popup,
        marker,
        point: [lng, lat],
        address,
      })
    },

    // 显示已保存的绘制数据
    showExistingData() {
      if (!_map) return
      
      this.clearDisplayedFeatures()
      
      const { wgsPosition, lineWgsPosition, pointWgsPosition, geoJsonData } = this.data

      
      // 根据templateId筛选图层并删除对应的数据
      this.filterAndRemoveDataByTemplateId()
      
      // 处理GeoJSON数据
      if (geoJsonData && geoJsonData.type === 'Feature') {
        this.addFeatureToMap(geoJsonData, this.getFeatureType(geoJsonData))
        return
      }
      
      // 显示线数据
      if (lineWgsPosition) {
        try {
          const lines = JSON.parse(lineWgsPosition)
          lines.forEach((line, index) => {
            const feature = {
              type: 'Feature',
              properties: { id: `existing-line-${index}` },
              geometry: {
                type: 'LineString',
                coordinates: line
              }
            }
            this.addFeatureToMap(feature, 'line')
          })
        } catch (e) {
          console.error('解析线数据失败:', e)
        }
      }
      
      // 显示面数据
      if (wgsPosition) {
        try {
          const polygons = JSON.parse(wgsPosition)
          polygons.forEach((polygon, index) => {
            const feature = {
              type: 'Feature',
              properties: { id: `existing-polygon-${index}` },
              geometry: {
                type: 'Polygon',
                coordinates: [polygon]
              }
            }
            this.addFeatureToMap(feature, 'polygon')
          })
        } catch (e) {
          console.error('解析面数据失败:', e)
        }
      }
      
      // 显示点数据
      if (pointWgsPosition) {
        try {
          const points = JSON.parse(pointWgsPosition)
          const showExistingMarkerCoords = []
          
          points.forEach((point, index) => {
            if (Array.isArray(point) && point.length >= 2) {
              const lngLat = new mapboxgl.LngLat(point[0], point[1])
              const address = point[2] || '' // 第三个元素是地址
              this.addMarker(lngLat, address)
              
              // 收集 showExistingData 显示的 marker 坐标
              showExistingMarkerCoords.push([point[0], point[1]])
            }
          })
          
          // 筛选并删除匹配的 multiPointFeatures
          this.filterMultiPointFeaturesByCoords(showExistingMarkerCoords)
        } catch (e) {
          console.error('解析点数据失败:', e)
        }
      }
      
      // 确保MapboxDraw处于选择模式，使要素可以被选中
      const draw = sharedDrawingManager.getDraw()
      if (draw) {
        draw.changeMode('simple_select')
      }
    },

    // 筛选并删除与 showExistingData marker 坐标匹配的 multiPointFeatures
    filterMultiPointFeaturesByCoords(showExistingMarkerCoords) {
      if (!Array.isArray(showExistingMarkerCoords) || showExistingMarkerCoords.length === 0) {
        return
      }
      

      
      // 通过事件通信，通知 useMapData 隐藏匹配的 multiPointFeatures markers
      const emitter = require('@/utils/event-bus').default
      emitter.emit('HIDE_MATCHING_MARKERS', showExistingMarkerCoords)
    },

    // 根据templateId筛选图层并删除对应的数据
    filterAndRemoveDataByTemplateId() {

      
      // 如果没有templateId，尝试从data中获取
      let effectiveTemplateId = this.templateId
      if (!effectiveTemplateId && this.data && this.data.templateId) {
        effectiveTemplateId = this.data.templateId

      }
      
      if (!effectiveTemplateId || !_map) {

        return
      }
      

      
      // 获取当前地图的所有图层
      const layers = _map.getStyle().layers || []
      const filteredLayers = []
      
      // 筛选出source等于templateId或templateId-labels的图层
      layers.forEach(layer => {
        const source = layer.source
        if (source === effectiveTemplateId || source === `${effectiveTemplateId}-labels`) {
          filteredLayers.push(layer)

        }
      })
      

      
      if (filteredLayers.length > 0) {
        // 如果存在匹配的图层，则删除this.data中对应的数据
        this.removeDataFromFilteredLayers(filteredLayers)
      }
    },

    // 从筛选出的图层中删除对应的数据
    removeDataFromFilteredLayers(filteredLayers) {
      if (!this.data) return
      

      
      // 获取所有筛选出的图层的源数据
      const sourcesToCheck = new Set()
      filteredLayers.forEach(layer => {
        if (layer.source) {
          sourcesToCheck.add(layer.source)
        }
      })
      

      
      // 遍历每个源，检查并删除对应的数据
      sourcesToCheck.forEach(sourceId => {
        try {
          const source = _map.getSource(sourceId)
          if (source && source._data && source._data.features) {
    
            
            // 根据this.data中的坐标信息，删除匹配的要素
            this.removeFeaturesFromSource(source, sourceId)
          }
        } catch (error) {
          console.warn(`检查源 ${sourceId} 时出错:`, error)
        }
      })
    },

    // 从源中删除匹配的要素
    removeFeaturesFromSource(source, sourceId) {
      const { wgsPosition, lineWgsPosition, pointWgsPosition } = this.data
      const featuresToRemove = []
      
      // 检查点数据
      if (pointWgsPosition) {
        try {
          const points = JSON.parse(pointWgsPosition)
          points.forEach(point => {
            if (Array.isArray(point) && point.length >= 2) {
              // 查找匹配的点要素
              source._data.features.forEach((feature, index) => {
                if (feature.geometry && feature.geometry.type === 'Point') {
                  const coords = feature.geometry.coordinates
                  if (coords && coords.length >= 2) {
                    // 检查坐标是否匹配（允许一定的误差）
                    const tolerance = 0.0001 // 约10米
                    if (Math.abs(coords[0] - point[0]) < tolerance && 
                        Math.abs(coords[1] - point[1]) < tolerance) {
                      featuresToRemove.push(index)
  
                    }
                  }
                }
              })
            }
          })
        } catch (e) {
          console.error('解析点数据失败:', e)
        }
      }
      
      // 检查线数据
      if (lineWgsPosition) {
        try {
          const lines = JSON.parse(lineWgsPosition)

          lines.forEach((line, lineIndex) => {
            if (Array.isArray(line) && line.length > 0) {
  
              // 查找匹配的线要素
              source._data.features.forEach((feature, index) => {
                if (feature.geometry) {
                  const tolerance = 0.0001
                  let isMatch = false

                  if (feature.geometry.type === 'LineString') {
                    // 处理单线
                    const coords = feature.geometry.coordinates
                    if (coords && coords.length > 0) {
                      if (coords.length === line.length) {
                        isMatch = coords.every((coord, i) =>
                          Math.abs(coord[0] - line[i][0]) <= tolerance &&
                          Math.abs(coord[1] - line[i][1]) <= tolerance
                        )
                      }
                    }
                  } else if (feature.geometry.type === 'MultiLineString') {
                    // 处理多线
                    const multiCoords = feature.geometry.coordinates
                    if (Array.isArray(multiCoords) && multiCoords.length > 0) {
                      // 在多线的每个线段中查找匹配
                      for (let i = 0; i < multiCoords.length; i++) {
                        const coords = multiCoords[i]
                        if (Array.isArray(coords) && coords.length > 0) {
                          if (coords.length === line.length) {
                            const segmentMatch = coords.every((coord, j) =>
                              Math.abs(coord[0] - line[j][0]) <= tolerance &&
                              Math.abs(coord[1] - line[j][1]) <= tolerance
                            )
                            if (segmentMatch) {
                              isMatch = true
                              break // 找到匹配的线段就跳出循环
                            }
                          }
                        }
                      }
                    }
                  }

                  if (isMatch) {
                    if (!featuresToRemove.includes(index)) {
                      featuresToRemove.push(index)

                    }
                  }
                }
              })
            }
          })
        } catch (e) {
          console.error('解析线数据失败:', e)
        }
      }
      
      // 检查面数据
      if (wgsPosition) {
        try {
          const polygons = JSON.parse(wgsPosition)
          polygons.forEach(polygon => {
            if (!Array.isArray(polygon) || polygon.length === 0) return

            source._data.features.forEach((feature, index) => {
              const geometry = feature.geometry
              if (!geometry) return

              const tolerance = 0.0001
              let matched = false

              if (geometry.type === 'Polygon') {
                const coords = geometry.coordinates
                if (Array.isArray(coords) && coords.length > 0 && coords[0].length === polygon.length) {
                  matched = coords[0].every((coord, i) =>
                    Math.abs(coord[0] - polygon[i][0]) <= tolerance &&
                    Math.abs(coord[1] - polygon[i][1]) <= tolerance
                  )
                }
              } else if (geometry.type === 'MultiPolygon') {
                const multiCoords = geometry.coordinates
                for (let i = 0; i < multiCoords.length; i++) {
                  const polygonCoords = multiCoords[i]
                  if (Array.isArray(polygonCoords) && polygonCoords.length > 0 && polygonCoords[0].length === polygon.length) {
                    const isMatch = polygonCoords[0].every((coord, j) =>
                      Math.abs(coord[0] - polygon[j][0]) <= tolerance &&
                      Math.abs(coord[1] - polygon[j][1]) <= tolerance
                    )
                    if (isMatch) {
                      matched = true
                      break // 一旦匹配就跳出 MultiPolygon 的循环
                    }
                  }
                }
              }

              if (matched) {
                if (!featuresToRemove.includes(index)) {
                  featuresToRemove.push(index)

                }
              }
            })
          })

        } catch (e) {
          console.error('解析面数据失败:', e)
        }
      }
      
      // 特殊处理：如果是template-labels图层，需要根据面数据和线数据的质心来删除对应的标签
      if (sourceId.endsWith('-labels')) {
        // 处理面数据的标签
        if (wgsPosition) {
          try {
            const polygons = JSON.parse(wgsPosition)

            polygons.forEach((polygon, polygonIndex) => {
              if (!Array.isArray(polygon) || polygon.length === 0) return

              // 计算多边形的质心
              const centroid = this.calculatePolygonCentroid(polygon)
              if (!centroid) {
                console.warn('无法计算多边形质心:', polygonIndex)
                return
              }



              // 在标签图层中查找匹配质心的标签要素
              source._data.features.forEach((feature, index) => {
                if (feature.geometry && feature.geometry.type === 'Point') {
                  const coords = feature.geometry.coordinates
                  if (coords && coords.length >= 2) {
                    // 增加容差，确保能匹配到标签
                    const tolerance = 0.001 // 增加到0.001
                    const distance = Math.sqrt(
                      Math.pow(coords[0] - centroid[0], 2) + 
                      Math.pow(coords[1] - centroid[1], 2)
                    )
                    
                    // 检查标签是否在多边形内部或附近
                    const isInsideOrNear = this.isPointInPolygon(coords, polygon) || distance < tolerance
                    
                    if (isInsideOrNear) {
                      if (!featuresToRemove.includes(index)) {
                        featuresToRemove.push(index)
  
                      }
                    }
                  }
                }
              })
            })
          } catch (e) {
            console.error('处理面标签图层时出错:', e)
          }
        }

        // 处理线数据的标签
        if (lineWgsPosition) {
          try {
            const lines = JSON.parse(lineWgsPosition)

            lines.forEach((line, lineIndex) => {
              if (!Array.isArray(line) || line.length < 2) return

              // 计算线的中点
              const midpoint = this.calculateLineMidpoint(line)
              if (!midpoint) {
                console.warn('无法计算线条中点:', lineIndex)
                return
              }



              // 在标签图层中查找匹配中点的标签要素
              source._data.features.forEach((feature, index) => {
                if (feature.geometry && feature.geometry.type === 'Point') {
                  const coords = feature.geometry.coordinates
                  if (coords && coords.length >= 2) {
                    // 增加容差，确保能匹配到标签
                    const tolerance = 0.001 // 增加到0.001
                    const distance = Math.sqrt(
                      Math.pow(coords[0] - midpoint[0], 2) + 
                      Math.pow(coords[1] - midpoint[1], 2)
                    )
                    
                    if (distance < tolerance) {
                      if (!featuresToRemove.includes(index)) {
                        featuresToRemove.push(index)
  
                      }
                    }
                  }
                }
              })
            })
          } catch (e) {
            console.error('处理线标签图层时出错:', e)
          }
        }
      }
      
      // 删除匹配的要素（从后往前删除，避免索引变化）
      if (featuresToRemove.length > 0) {

        featuresToRemove.sort((a, b) => b - a).forEach(index => {
          source._data.features.splice(index, 1)
        })
        
        // 更新源数据
        source.setData(source._data)
      }
    },

    // 计算多边形质心的辅助方法
    calculatePolygonCentroid(coordinates) {
      if (!Array.isArray(coordinates) || coordinates.length === 0) return null
      
      // 如果坐标点太少，使用简单的平均值
      if (coordinates.length < 3) {
        const avgX = coordinates.reduce((sum, coord) => sum + coord[0], 0) / coordinates.length
        const avgY = coordinates.reduce((sum, coord) => sum + coord[1], 0) / coordinates.length
        return [avgX, avgY]
      }
      
      let area = 0
      let centroidX = 0
      let centroidY = 0
      
      for (let i = 0; i < coordinates.length; i++) {
        const j = (i + 1) % coordinates.length
        const xi = coordinates[i][0]
        const yi = coordinates[i][1]
        const xj = coordinates[j][0]
        const yj = coordinates[j][1]
        
        const cross = xi * yj - xj * yi
        area += cross
        centroidX += (xi + xj) * cross
        centroidY += (yi + yj) * cross
      }
      
      area /= 2
      if (Math.abs(area) < 1e-10) {
        // 如果面积太小，使用简单的平均值
        const avgX = coordinates.reduce((sum, coord) => sum + coord[0], 0) / coordinates.length
        const avgY = coordinates.reduce((sum, coord) => sum + coord[1], 0) / coordinates.length
        return [avgX, avgY]
      }
      
      centroidX /= (6 * area)
      centroidY /= (6 * area)
      

      return [centroidX, centroidY]
    },

    // 计算线中点的辅助方法
    calculateLineMidpoint(coordinates) {
      if (!Array.isArray(coordinates) || coordinates.length < 2) return null
      

      
      // 如果只有两个点，直接计算中点
      if (coordinates.length === 2) {
        const midpoint = [
          (coordinates[0][0] + coordinates[1][0]) / 2,
          (coordinates[0][1] + coordinates[1][1]) / 2
        ]
  
        return midpoint
      }
      
      // 如果有多于两个点，计算总长度并找到中点
      let totalLength = 0
      const segmentLengths = []
      
      for (let i = 0; i < coordinates.length - 1; i++) {
        const dx = coordinates[i + 1][0] - coordinates[i][0]
        const dy = coordinates[i + 1][1] - coordinates[i][1]
        const segmentLength = Math.sqrt(dx * dx + dy * dy)
        segmentLengths.push(segmentLength)
        totalLength += segmentLength
      }
      

      
      if (totalLength === 0) {
        // 如果总长度为0，使用简单的平均值
        const avgX = coordinates.reduce((sum, coord) => sum + coord[0], 0) / coordinates.length
        const avgY = coordinates.reduce((sum, coord) => sum + coord[1], 0) / coordinates.length

        return [avgX, avgY]
      }
      
      // 找到中点所在的线段
      let currentLength = 0
      const targetLength = totalLength / 2
      
      for (let i = 0; i < segmentLengths.length; i++) {
        if (currentLength + segmentLengths[i] >= targetLength) {
          // 中点在这个线段上
          const ratio = (targetLength - currentLength) / segmentLengths[i]
          const startPoint = coordinates[i]
          const endPoint = coordinates[i + 1]
          
          const midpoint = [
            startPoint[0] + ratio * (endPoint[0] - startPoint[0]),
            startPoint[1] + ratio * (endPoint[1] - startPoint[1])
          ]
  
          return midpoint
        }
        currentLength += segmentLengths[i]
      }
      
      // 如果没找到，返回最后一个点
      const lastPoint = coordinates[coordinates.length - 1]
      
      return lastPoint
    },

    // 获取要素类型
    getFeatureType(feature) {
      if (!feature.geometry) return 'line'
      
      switch (feature.geometry.type) {
        case 'Point':
        case 'MultiPoint':
          return 'point'
        case 'LineString':
        case 'MultiLineString':
          return 'line'
        case 'Polygon':
        case 'MultiPolygon':
          return 'polygon'
        default:
          return 'line'
      }
    },

    // 添加要素到地图
    addFeatureToMap(feature, type) {
      if (!_map) return
      
      // 如果是点类型，使用addMarker方法，不添加到MapboxDraw中
      if (type === 'point') {
        if (feature.geometry.type === 'Point') {
          const coordinates = feature.geometry.coordinates
          const lngLat = new mapboxgl.LngLat(coordinates[0], coordinates[1])
          const address = feature.properties?.address || ''
          this.addMarker(lngLat, address)
        } else if (feature.geometry.type === 'MultiPoint') {
          feature.geometry.coordinates.forEach((coord, index) => {
            const lngLat = new mapboxgl.LngLat(coord[0], coord[1])
            const address = feature.properties?.address || ''
            this.addMarker(lngLat, address)
          })
        }
        return
      }
      
      const sourceId = `existing-${type}-${Date.now()}-${Math.random()}`
      const layerId = `existing-${type}-layer-${Date.now()}-${Math.random()}`
      
      _map.addSource(sourceId, {
        type: 'geojson',
        data: {
          type: 'FeatureCollection',
          features: [feature]
        }
      })
      
      const layerStyle = this.getLayerStyle(type)
      _map.addLayer({
        id: layerId,
        type: type === 'polygon' ? 'fill' : 'line',
        source: sourceId,
        paint: layerStyle.paint,
        layout: layerStyle.layout
      })
      
      // 将要素添加到MapboxDraw中，使其可以被选中和编辑
      const draw = sharedDrawingManager.getDraw()
      if (draw) {
        // 为显示要素添加特殊标记，用于后续识别和清理
        feature.properties.isDisplayFeature = true
        draw.add(feature)
        
        // 获取添加后的要素ID，用于后续精确删除
        const allData = draw.getAll()
        const addedFeature = allData.features.find(f => 
          f.properties.isDisplayFeature && 
          f.geometry.type === feature.geometry.type &&
          JSON.stringify(f.geometry.coordinates) === JSON.stringify(feature.geometry.coordinates)
        )
        
        if (addedFeature) {
          displayedFeatures.push({ 
            sourceId, 
            layerId, 
            type, 
            mapboxDrawId: addedFeature.id 
          })
        } else {
          displayedFeatures.push({ sourceId, layerId, type })
        }
      } else {
        displayedFeatures.push({ sourceId, layerId, type })
      }
    },

    // 获取图层样式
    getLayerStyle(type) {
      const baseStyle = {
        paint: {
          'line-color': 'rgba(0,186,255,.8)',
          'line-width': 3,
          'line-opacity': 0.8
        },
        layout: {
          'line-join': 'round',
          'line-cap': 'round'
        }
      }
      
      if (type === 'polygon') {
        return {
          paint: {
            'fill-color': 'rgba(0,186,255,.2)',
            'fill-opacity': 0.3,
            'fill-outline-color': '#00BAFF'
          },
          layout: {}
        }
      }
      
      return baseStyle
    },

    // 清除显示的要素
    clearDisplayedFeatures() {
      if (!_map) return
      
      // 清除地图图层和源
      displayedFeatures.forEach(({ sourceId, layerId }) => {
        if (_map.getLayer(layerId)) {
          _map.removeLayer(layerId)
        }
        if (_map.getSource(sourceId)) {
          _map.removeSource(sourceId)
        }
      })
      
      // 清除MapboxDraw中的显示要素
      const draw = sharedDrawingManager.getDraw()
      if (draw) {
        const allData = draw.getAll()
        const featuresToRemove = []
        
        allData.features.forEach((feature) => {
          // 删除那些标记为显示要素的要素
          if (feature.properties && feature.properties.isDisplayFeature) {
            featuresToRemove.push(feature.id)
          }
        })
        
        featuresToRemove.forEach(id => {
          try {
            draw.delete(id)
          } catch (error) {
            console.warn('Failed to remove display feature:', error)
          }
        })
      }
      
      displayedFeatures = []
    },

    // 清除指定选中要素对应的显示要素
    clearSelectedDisplayedFeatures(selectedFeatureId) {
      if (!_map || !selectedFeatureId) return
      
      const draw = sharedDrawingManager.getDraw()
      if (!draw) return
      
      // 获取选中的要素
      const selectedFeature = draw.get(selectedFeatureId)
      if (!selectedFeature) return
      
      // 计算选中要素的几何中心点，用于匹配对应的显示要素
      let centerPoint
      if (selectedFeature.geometry.type === 'Polygon') {
        centerPoint = this.calculatePolygonCentroid(selectedFeature.geometry.coordinates[0])
      } else if (selectedFeature.geometry.type === 'LineString') {
        centerPoint = this.calculateLineMidpoint(selectedFeature.geometry.coordinates)
      } else if (selectedFeature.geometry.type === 'Point') {
        centerPoint = selectedFeature.geometry.coordinates
      }
      
      if (!centerPoint) return
      
      // 查找并删除对应的显示要素
      const allData = draw.getAll()
      const featuresToRemove = []
      
      allData.features.forEach((feature) => {
        if (feature.properties && feature.properties.isDisplayFeature) {
          // 检查是否是同一个要素的显示版本
          let featureCenter
          if (feature.geometry.type === 'Polygon') {
            featureCenter = this.calculatePolygonCentroid(feature.geometry.coordinates[0])
          } else if (feature.geometry.type === 'LineString') {
            featureCenter = this.calculateLineMidpoint(feature.geometry.coordinates)
          } else if (feature.geometry.type === 'Point') {
            featureCenter = feature.geometry.coordinates
          }
          
          // 如果中心点匹配（允许小的误差），则删除这个显示要素
          if (featureCenter && this.pointsMatch(centerPoint, featureCenter)) {
            featuresToRemove.push(feature.id)
          }
        }
      })
      
      // 删除匹配的显示要素
      featuresToRemove.forEach(id => {
        try {
          draw.delete(id)
        } catch (error) {
          console.warn('Failed to remove selected display feature:', error)
        }
      })
      
      // 同时删除对应的地图图层和源
      // 这里我们需要找到对应的图层和源，但由于displayedFeatures数组没有存储要素ID的映射关系
      // 我们只能通过清除所有显示要素的图层来解决
      // 这是一个简化的解决方案，实际应用中可能需要更精确的映射
      this.clearDisplayedFeatures()
    },

    // 根据MapboxDraw要素ID清除对应的显示要素
    clearSpecificDisplayedFeature(mapboxDrawFeatureId) {
      if (!_map || !mapboxDrawFeatureId) return
      
      // 查找对应的显示要素记录
      const featureRecord = displayedFeatures.find(f => f.mapboxDrawId === mapboxDrawFeatureId)
      
      if (featureRecord) {
        // 删除对应的地图图层和源
        if (_map.getLayer(featureRecord.layerId)) {
          _map.removeLayer(featureRecord.layerId)
        }
        if (_map.getSource(featureRecord.sourceId)) {
          _map.removeSource(featureRecord.sourceId)
        }
        
        // 从displayedFeatures数组中移除该记录
        const index = displayedFeatures.findIndex(f => f.mapboxDrawId === mapboxDrawFeatureId)
        if (index > -1) {
          displayedFeatures.splice(index, 1)
        }
        

      } else {
        // 如果没有找到精确匹配的记录，尝试通过几何匹配来清除
        console.warn('未找到对应的显示要素记录，尝试通过几何匹配清除:', mapboxDrawFeatureId)
        this.clearDisplayedFeaturesByGeometry(mapboxDrawFeatureId)
      }
    },

    // 通过几何匹配清除显示要素（备用方案）
    clearDisplayedFeaturesByGeometry(mapboxDrawFeatureId) {
      const draw = sharedDrawingManager.getDraw()
      if (!draw) return
      
      // 获取被删除的要素的几何信息
      const deletedFeature = draw.get(mapboxDrawFeatureId)
      if (!deletedFeature) return
      
      // 计算几何中心点
      let centerPoint
      if (deletedFeature.geometry.type === 'Polygon') {
        centerPoint = this.calculatePolygonCentroid(deletedFeature.geometry.coordinates[0])
      } else if (deletedFeature.geometry.type === 'LineString') {
        centerPoint = this.calculateLineMidpoint(deletedFeature.geometry.coordinates)
      } else if (deletedFeature.geometry.type === 'Point') {
        centerPoint = deletedFeature.geometry.coordinates
      }
      
      if (!centerPoint) return
      
      // 查找并删除匹配的显示要素
      const featuresToRemove = []
      displayedFeatures.forEach((featureRecord, index) => {
        // 尝试通过源数据获取几何信息进行匹配
        try {
          const source = _map.getSource(featureRecord.sourceId)
          if (source && source._data && source._data.features) {
            const sourceFeature = source._data.features[0] // 假设每个源只有一个要素
            if (sourceFeature && sourceFeature.geometry) {
              let sourceCenterPoint
              if (sourceFeature.geometry.type === 'Polygon') {
                sourceCenterPoint = this.calculatePolygonCentroid(sourceFeature.geometry.coordinates[0])
              } else if (sourceFeature.geometry.type === 'LineString') {
                sourceCenterPoint = this.calculateLineMidpoint(sourceFeature.geometry.coordinates)
              } else if (sourceFeature.geometry.type === 'Point') {
                sourceCenterPoint = sourceFeature.geometry.coordinates
              }
              
              // 如果中心点匹配，则删除这个显示要素
              if (sourceCenterPoint && this.pointsMatch(centerPoint, sourceCenterPoint)) {
                if (_map.getLayer(featureRecord.layerId)) {
                  _map.removeLayer(featureRecord.layerId)
                }
                if (_map.getSource(featureRecord.sourceId)) {
                  _map.removeSource(featureRecord.sourceId)
                }
                featuresToRemove.push(index)
        
              }
            }
          }
        } catch (error) {
          console.warn('获取源数据时出错:', error)
        }
      })
      
      // 从displayedFeatures数组中移除记录
      featuresToRemove.sort((a, b) => b - a).forEach(index => {
        displayedFeatures.splice(index, 1)
      })
      
      if (featuresToRemove.length === 0) {
        console.warn('未找到匹配的显示要素进行删除')
      }
    },

    // 检查两个点是否匹配（允许小的误差）
    pointsMatch(point1, point2, tolerance = 0.0001) {
      const match = Math.abs(point1[0] - point2[0]) < tolerance && 
                   Math.abs(point1[1] - point2[1]) < tolerance

      return match
    },

    // 检查点是否在多边形内部（射线法）
    isPointInPolygon(point, polygon) {
      if (!Array.isArray(polygon) || polygon.length < 3) return false
      
      const [x, y] = point
      let inside = false
      
      for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {
        const [xi, yi] = polygon[i]
        const [xj, yj] = polygon[j]
        
        if (((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi)) {
          inside = !inside
        }
      }
      
      return inside
    },



    // 设置编辑模式
    setEditMode(enabled) {
      this.isEditMode = enabled
      
      // 更新现有标记点的删除按钮状态
      markers.forEach(marker => {
        if (marker.popup && marker.popup._content) {
          // 这里可以更新popup中的删除按钮状态
          // 由于popup是动态创建的，可能需要重新创建
        }
      })
      
      // 确保MapboxDraw处于正确的模式
      const draw = sharedDrawingManager.getDraw()
      if (draw) {
        if (enabled) {
          // 编辑模式：允许选择和编辑
          draw.changeMode('simple_select')
        } else {
          // 非编辑模式：只允许选择，不允许编辑
          draw.changeMode('simple_select')
        }
      }
    },

    addDraw(type) {
      if (!this.mapReady || !_map) {
        console.warn('地图未准备好，无法绘制')
        return
      }

      this.stopDrawing()

      this.currentDrawType = type
      // 不要重置标记，保持现有数据的显示状态
      // this.existingDataShown = false

      const draw = sharedDrawingManager.init(_map)

      // 清除之前的事件监听，避免重复绑定
      sharedDrawingManager.removeAllEventListeners()

      this.handlingCreate = false

      sharedDrawingManager.addEventListener('draw.create', () => {
        if (this.handlingCreate) return
        this.handlingCreate = true


        
        // 获取当前所有要素，检查新创建的要素
        const allData = draw.getAll()
        allData.features.forEach((feature, index) => {

        })

        // 切换为选择模式结束绘制
        draw.changeMode('simple_select')

        // 如果需要连续绘制，请解开下面注释
        // setTimeout(() => {
        //   this.startDrawMode()
        //   this.handlingCreate = false
        // }, 0)

        // 如果不连续绘制，解锁放在这里
        this.handlingCreate = false
      })



      if (type === 'point') {
        _map.on('click', this.handlePointClick)
      } else {
        _map.off('click', this.handlePointClick)
      }

      // 立即启动绘制模式
      this.startDrawMode()
    },

    startDrawMode() {
      const draw = sharedDrawingManager.getDraw()
      if (!draw) return

      switch (this.currentDrawType) {
        case 'line':
        case 'polyline':
          draw.changeMode('draw_line_string')
          break
        case 'polygon':
          draw.changeMode('draw_polygon')
          break
        case 'point':
          draw.changeMode('simple_select') // 点绘制用地图点击事件触发
          break
      }
    },

    stopDrawing() {
      if (!_map) return

      _map.off('click', this.handlePointClick)

      sharedDrawingManager.removeAllEventListeners()

      const draw = sharedDrawingManager.getDraw()
      if (draw) {
        draw.changeMode('simple_select')
      }

      this.currentDrawType = null
      this.handlingCreate = false
    },

    handlePointClick(event) {

      // 只有在编辑模式下才能添加点
      if (this.isEditMode) {
        this.addMarker(event.lngLat)
      }
    },

    getDraw() {
      return sharedDrawingManager.getDraw()
    },

    // 确保绘制实例已初始化
    ensureDrawInitialized() {
      if (!_map) {
        console.log('Map not ready, cannot initialize draw')
        return
      }
      
      let draw = sharedDrawingManager.getDraw()
      if (!draw) {
        console.log('Initializing draw instance')
        draw = sharedDrawingManager.init(_map)
      }
      
      return draw
    },

    // 清除所有标记点
    clearAllMarkers() {
      markers.forEach((m) => {
        m.marker.remove()
        m.popup.remove()
      })
      markers = []
    },

    // 获取标记点数据
    getMarkers() {
      return markers
    },

    // 清除所有显示的内容（包括要素和标记点）
    clearAll() {
      this.clearDisplayedFeatures()
      this.clearAllMarkers()
      
      // 清除MapboxDraw中的所有要素
      const draw = sharedDrawingManager.getDraw()
      if (draw) {
        draw.deleteAll()
      }
      
      // 重置标记，允许重新显示现有数据
      this.existingDataShown = false
      
      // 通知恢复显示被隐藏的 multiPointFeatures markers
      const emitter = require('@/utils/event-bus').default
      emitter.emit('RESTORE_HIDDEN_MARKERS')
    },

    getDrawResult() {
      const draw = sharedDrawingManager.getDraw()
      if (!draw) return null

      const allData = draw.getAll()

      const lines = []
      const polygons = []
      const displayFeatures = []
      const newFeatures = []

      // 处理所有要素，简化逻辑
      allData.features.forEach((feature) => {
        // 直接处理所有要素，不进行额外的存在性检查
        if (feature.properties && feature.properties.isDisplayFeature) {
          displayFeatures.push(feature)
        } else {
          newFeatures.push(feature)
        }

        const type = feature.geometry.type
        const coords = feature.geometry.coordinates

        // 点数据以 addmarker 为准，不在这里处理
        if (type === 'LineString') {
          lines.push(coords)
        } else if (type === 'Polygon') {
          polygons.push(coords[0]) // polygon 是嵌套数组
        }
      })

      // 根据情况返回不同的数据
      let resultFeatures = []
      
      if (displayFeatures.length > 0 && newFeatures.length > 0) {
        // 情况1：既有初始化图形，又有新绘制的图形
        resultFeatures = [...displayFeatures, ...newFeatures] // 合并所有存在的要素
      } else if (displayFeatures.length > 0 && newFeatures.length === 0) {
        // 情况2：只有初始化图形，没有新绘制的图形
        resultFeatures = displayFeatures // 只包含显示要素
      } else if (displayFeatures.length === 0 && newFeatures.length > 0) {
        // 情况3：只有新绘制的图形，没有初始化图形
        resultFeatures = newFeatures // 只包含新绘制的要素
      } else {
        // 情况4：没有任何图形
        resultFeatures = []
      }

      const resultGeoJson = {
        type: 'FeatureCollection',
        features: resultFeatures
      }

      // 重新计算坐标数据，确保包含所有要素的坐标
      const allFeatures = [...displayFeatures, ...newFeatures]
      const finalLines = []
      const finalPolygons = []

      allFeatures.forEach((feature) => {
        const type = feature.geometry.type
        const coords = feature.geometry.coordinates

        // 点数据以 addmarker 为准，不在这里处理
        if (type === 'LineString') {
          finalLines.push(coords)
        } else if (type === 'Polygon') {
          finalPolygons.push(coords[0]) // polygon 是嵌套数组
        }
      })

      // 处理标记点数据（点数据以 addmarker 为准）
      const finalPoints = []
      markers.forEach((marker) => {
        if (marker.point && Array.isArray(marker.point)) {
          finalPoints.push(marker.point)
        }
      })

      return {
        geoJson: resultGeoJson,
        lineWgsPosition: JSON.stringify(finalLines),
        wgsPosition: JSON.stringify(finalPolygons),
        pointWgsPosition: JSON.stringify(finalPoints),
      }
    }
  }
}
</script>
